package member

import (
	"errors"
	"stormragetech/dawn/common"
	"time"

	mgo "gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

// SignupHandle 注册操作
func SignupHandle(username string, pwd string, realname string, deptID string) error {

	u, err := FindByUsername(username)
	if err != nil && err != mgo.ErrNotFound {
		return errors.New("注册失败")
	}

	if err != mgo.ErrNotFound {
		return errors.New("用户名已存在")
	}

	salt := common.Salt()
	pwd = common.GenPass(pwd, salt)
	u = SysUser{bson.NewObjectId(), common.UUID(), username, pwd, salt, realname, deptID, time.Now(), false}
	err = InsUser(u)
	if err != nil {
		return errors.New("注册失败")
	}

	return nil
}

// LoginHandle 登录操作
func LoginHandle(username string, pwd string) (string, error) {

	u, err := FindByUsername(username)
	if err == mgo.ErrNotFound {
		return "", errors.New("用户名不存在")
	}

	if err != nil {
		return "", errors.New("登录失败")
	}

	pwd = common.GenPass(pwd, u.Salt)
	if pwd != u.Password {
		return "", errors.New("用户名密码错误")
	}

	token, err := SetToken(u.UserID)
	if err != nil {
		return "", errors.New("登录失败")
	}
	return token, nil
}
